package com.youkeda.yikao.web.config;

import com.youkeda.yikao.web.dataobject.ChenzikangUesrSystem;
import org.apache.catalina.User;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：chenzikang
 * @date ： 2019/8/31 14:02
 */

@Component
public class AuthHanderlnterceptor implements HandlerInterceptor {


    /**
     *
     * 方法拦截类
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //先判断是不是HandlerMethod类型
        if (handler instanceof HandlerMethod) {

            //强制转换成HandlerMethod类型
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            //判断该方法是否有NeedLogin注释
            NeedLogin needLogin = handlerMethod.getMethodAnnotation(NeedLogin.class);

            if (needLogin != null) {

                //从session中取出用户信息
                ChenzikangUesrSystem chenzikangUesrSystem = (ChenzikangUesrSystem) request.getSession().getAttribute("user");

                //如果没有取到，就跳转登录页面，并返回false
                if (chenzikangUesrSystem == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }

        }

        return true;
    }
}
